import urllib

from django import forms

from app import widgets

# Maximum forms fields length
MAX_URL = 2000
MAX_OWNER = 1000
MAX_DESCRIPTION = 10000
MAX_TAGS = 2000
MAX_DOMAIN = 2000


class UrlField(forms.CharField):
	def to_python(self, value):
		# unquote() replaces %xx escapes with their single-byte equivalents
		# decode() converts a string of bytes in the utf8 representation into a unicode string
		try:
			url = urllib.unquote(value).decode('utf8')
		except:
			url = value
		return url

class TagsField(forms.CharField):
	def to_python(self, value):
		# convert string (comma-separated list) into a python list
		if not value:
			return []
		tags = value.strip().split(',')

		tags = [tag.strip() for tag in tags]
		tags = filter(None, tags)
		return tags


class LinkBaseForm(forms.Form):
	url = UrlField(max_length=MAX_URL, 
			widget=forms.TextInput(attrs={'size': 80}))
	description = forms.CharField(required=False,
			max_length=MAX_DESCRIPTION,
			widget=forms.Textarea(attrs={'cols': 80}))
	tags = TagsField(max_length=MAX_TAGS, required=False, 
			widget=forms.TextInput(attrs={'size': 80}),
			help_text='Tags: Comma-separated list')
	attributes = forms.CharField(required=False,
			widget=widgets.AttributesInput(
					key_attrs={'class': 'attr-key-input', 'size': 15},
					val_attrs={'class': 'attr-value-input', 'size': 35},
			),
			help_text='Attributes: Key-value pairs')

	private = forms.BooleanField(required=False, initial=False)


class NewForm(LinkBaseForm):
	pass

class EditForm(LinkBaseForm):
	pass

# options for sorting search results
ORDER_CHOICES = (
    'owner',
    'created',
    'modified',
)

class SearchForm(forms.Form):
	cursor = forms.CharField(required=False,
			widget=forms.HiddenInput(attrs={'value': ''}))
	tags = TagsField(max_length=MAX_TAGS, required=False, 
			widget=forms.TextInput(attrs={'size': 40}),
			help_text='Tags: Comma-separated list')
	owner = forms.CharField(max_length=MAX_OWNER, required=False, 
			widget=forms.TextInput(attrs={'size': 40}))
	domain = forms.CharField(max_length=MAX_DOMAIN, required=False, 
			widget=forms.TextInput(attrs={'size': 40}))
	private = forms.NullBooleanField(required=False)
	order = forms.ChoiceField(
			required=False,
			choices=sum(
				([(x, x), ('-' + x, '-' + x)] for x in ORDER_CHOICES),
				[('', '(default)')]))

